package net.prasenjit.test.webservice.validation;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.*;
import org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor;
import org.xml.sax.SAXParseException;

/**
 * Created with IntelliJ IDEA.
 * User: PPurohit
 * Date: 8/21/14
 * Time: 12:39 PM
 * To change this template use File | Settings | File Templates.
 */
public class ValidatingInterceptor extends PayloadValidatingInterceptor {

    private static final Logger LOGGER = LogManager.getLogger();
    private boolean faultOnResponseError;

    @Override
    protected boolean handleResponseValidationErrors(MessageContext messageContext, SAXParseException[] errors) {
        if (faultOnResponseError) {
            return super.handleResponseValidationErrors(messageContext, errors);
        } else {
            if (messageContext.getResponse() instanceof SoapMessage) {
                SoapMessage response = (SoapMessage) messageContext.getResponse();
                SoapBody body = response.getSoapBody();
                SoapFault fault = body.addClientOrSenderFault(getFaultStringOrReason(), getFaultStringOrReasonLocale());
                if (getAddValidationErrorDetail()) {
                    SoapFaultDetail detail = fault.addFaultDetail();
                    for (SAXParseException error : errors) {
                        LOGGER.error("XML validation error on request: {}", error.getMessage());
                        SoapFaultDetailElement detailElement = detail.addFaultDetailElement(getDetailElementName());
                        detailElement.addText(error.getMessage());
                    }
                }
            } else {
                for (SAXParseException error : errors) {
                    LOGGER.error("XML validation error on request: {}", error.getMessage());
                }
            }
            return false;
        }
    }

    public void setFaultOnResponseError(boolean faultOnResponseError) {
        this.faultOnResponseError = faultOnResponseError;
    }
}
